package DesignPatterns;

public class Singleton {

    //加volatile是为了禁止指令重排
    private static volatile Singleton singleton = null;

    private Singleton() {
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

}

class Main {
    public static void main(String[] args) {
        TestSingleton testSingleton = new TestSingleton();
        new Thread(testSingleton).start();
        new Thread(testSingleton).start();
        new Thread(testSingleton).start();
        new Thread(testSingleton).start();
        new Thread(testSingleton).start();
        new Thread(testSingleton).start();
    }
}

class TestSingleton implements Runnable {
    @Override
    public void run() {
        Singleton singleton = Singleton.getSingleton();
        System.out.println(singleton.hashCode());
    }
}